package cn.fr4nk.crawler.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.fr4nk.crawler.task.Handler;

public abstract class HandlerRunnable<T> implements Runnable {

	private static Log log = LogFactory.getLog(HandlerRunnable.class);

	protected Handler<T> handler;

	public Handler<T> getHandler() {
		return handler;
	}

	protected abstract T getHandleTask() throws Exception;

	@Override
	public void run() {
		while (true) {
			T result = null;
			try {
				log.debug(">>>> 等待队列返回结果 >>>>>");
				result = getHandleTask(); // blocked
				log.debug("<<<<<  队列返回结果,开始处理...");
				handler.handle(result);
				log.debug(">>>>>> 队列返回结果,处理完成 >>>>>");
			} catch (InterruptedException e) {
				log.warn(e);
				Thread.currentThread().interrupt();
			} catch (Exception e) {
				log.error("处理result出错: " + e.getMessage());
				log.error(e);
			}
		}
	}

	public void setHandler(Handler<T> handler) {
		this.handler = handler;
	}

}
